import utils from '@/config/cookieUtils'
// import $ from 'jquery'
var CryptoJS = require('crypto-js')
var headConfig = {headers: {'content-type': 'application/x-www-form-urlencoded'}}

export default {
  data () {
    return {
      // appId: '25c41adc8f4148bdbcec2033d4aa040f',
      appId: 'a91ffd2c9af244c7bf8c0dc120828e18', // 开发环境
      // appId: 'd34f5f43c5f741278ebc10b3e6972177', // 现网环境
      clientId: 'd34f5f43c5f741278ebc10b3e6972177',
      clientSecret: '8802c52da0b07788',
      loginUrl: '',
      wxgzhAppId: 'wxdbfff9bf396fafdb', // 微信公众号ID
      wxgzhAppKey: 'c701172d17da483096da8db6c1482bad' // 微信公众号key
    }
  },
  created () {
    let vm = this
    // $.getJSON('/static/qizhongfenxi/json/config.json', function (data) {
    // vm.loginUrl = 'http://192.168.102.105:9000/' // data.loginUrl //之前
    // vm.loginUrl = 'https://test204.teewon.net:7877/' // 测试环境
    vm.loginUrl = 'http://111.6.28.242:9000/' // data.loginUrl 现网环境
    // vm.loginUrl = 'http://192.168.102.109:19000/' // data.loginUrl 开发环境
    // })
  },
  mounted () {},
  methods: {
    bindAccountByWX (code) {
      let vm = this
      let req = {'code': code, 'pubAppId': vm.wxgzhAppId, 'role': '1000000003'}
      vm.$axios.post('/openapi-uc/publicAccount/bind', req).then((resp) => {
      }).catch((err) => {
        console.log(err)
      })
    },
    // 用户名密码登录
    userPwdLoginRequest: function (loginName, pwd, successFunc, errorFunc) {
      let vm = this
      // 对密码进行加密
      let key = CryptoJS.enc.Utf8.parse(vm.clientSecret)
      let encryptPassword = CryptoJS.AES.encrypt(pwd, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      if (vm.autoLogin) {
        utils.set('LOGIN_NAME', vm.loginUser)
        utils.set('LOGIN_PASSWORD', encryptPassword)
      }
      var loginParam = 'client_id=' + vm.appId + '&client_secret=' + vm.clientSecret + '&grant_type=password&lgxm=' + loginName + '&lgmm=' + encodeURIComponent(encryptPassword) + '&check_weak_pwd=1'
      if (vm.userId) {
        loginParam = loginParam + '&uid=' + vm.userId + '&version=01'
        if (this.autoLogin) {
          utils.set('LOGIN_USERID', vm.userId)
        }
      } else {
        loginParam = loginParam + '&version=01'
      }
      vm.$axios.post('/openapi-uc/oauth/token?' + loginParam, {}, headConfig)
        .then(function (response) {
          if (successFunc) {
            successFunc(response)
          }
        })
        .catch(function (error) {
          if (errorFunc) {
            errorFunc(error)
          }
          console.log('/openapi-uc/oauth/token error: ' + JSON.stringify(error))
        })
    },
    // 信任码获取token接口
    loginByAccreditCode: function (accreditCode, successCallback, failedCallback) {
      if (accreditCode) {
        let headConfig = {headers: {'content-type': 'application/x-www-form-urlencoded'}}
        let loginParam = 'client_id=' + this.appId + '&client_secret=' + this.clientSecret + '&grant_type=client_credentials&accredit_code=' + accreditCode + '&version=01'
        this.$axios.post('/openapi-uc/oauth/token?' + loginParam, {}, headConfig)
          .then(function (response) {
            if (successCallback) {
              successCallback(response)
            }
          }).catch(function (error) {
            console.log('accreditCodeLogin error: ' + error)
            if (failedCallback) {
              failedCallback(error)
            }
          })
      } else {
        if (failedCallback) {
          failedCallback('信任码为空')
        }
      }
    },
    // openId获取token接口 - 微信登录
    loginByOpenId: function (openId, successCallback, failedCallback) {
      if (openId) {
        let headConfig = {headers: {'content-type': 'application/x-www-form-urlencoded'}}
        let loginParam = 'client_id=' + this.appId + '&client_secret=' + this.clientSecret + '&grant_type=public_account&&pubAppId=' + this.wxgzhAppId + '&code=' + openId
        this.$axios.post('/openapi-uc/oauth/token?' + loginParam, {}, headConfig)
          .then(function (response) {
            if (successCallback) {
              successCallback(response)
            }
          }).catch(function (error) {
            console.log('loginByOpenId error: ' + error)
            if (failedCallback) {
              failedCallback(error)
            }
          })
      } else {
        if (failedCallback) {
          failedCallback('openId为空')
        }
      }
    },
    // token 获取用户接口
    getUserInfoByToken: function (accessToken, successCallback, failedCallback) {
      this.$axios.get('/openapi-uc/uc/getUserByToken/' + accessToken)
        .then(function (response) {
          console.log(JSON.stringify(response))
          utils.set('jczc_curr_token', accessToken)
          if (successCallback) {
            successCallback(response)
          }
        })
        .catch(function (error) {
          if (failedCallback) {
            failedCallback(error)
          }
        })
    },
    // 获取用户权限接口
    getUserRightRequest: function (successCallback, failedCallback) {
      let vm = this
      let req = {'addrType': '2', 'appId': vm.appId, 'roleId': vm.getUserCurrentRoleId()}
      vm.$axios.post('/openapi-uc/uc/getUserRightList', req)
        .then(function (response) {
          let pathStr = ''
          for (let i = 0; i < response.data.pageInfo.list.length; i++) {
            if (response.data.pageInfo.list[i].menuPath) {
              pathStr += response.data.pageInfo.list[i].menuPath + ','
            }
          }
          utils.set('jczc_curr_rightarray', pathStr)

          if (successCallback) {
            successCallback(response)
          }
        })
        .catch(function (error) {
          if (failedCallback) {
            failedCallback(error)
          }
        })
    },
    getUrlParameter: function (url, name) {
      if (url.indexOf('?') !== -1) {
        let strs = []
        var str = url.substr(url.indexOf('?') + 1)
        strs = str.split('&')
        let key
        for (let i = 0; i < strs.length; i++) {
          key = strs[i].split('=')[0]
          if (key === name) {
            return strs[i].split('=')[1]
          }
        }
      }
      return null
    },
    clearCookieInfo: function () {
      utils.set('jczc_curr_token', '')
      utils.set('jczc_curr_userid', '')
      utils.set('jczc_curr_orgid', '')
      utils.set('jczc_curr_realname', '')
      utils.set('jczc_curr_tenantid', '')
      utils.set('jczc_curr_orgname', '')
      utils.set('jczc_curr_roleid', '')
      utils.set('jczc_curr_roleidlist', '')
      utils.set('jczc_curr_areaname', '')
      utils.set('jczc_curr_areaid', '')
      utils.set('jczc_curr_gradeid', '')
      utils.set('jczc_curr_subjectid', '')
      utils.set('jczc_userrole_exts', '')
    },
    setUserCookie: function (user) {
      console.log('user = ', user)
      utils.set('jczc_curr_userid', user.userId)
      utils.set('jczc_curr_orgid', user.orgId)
      utils.set('jczc_curr_realname', user.realName)
      utils.set('jczc_curr_tenantid', user.branchCode)
      utils.set('jczc_curr_orgname', user.orgName)
      utils.set('jczc_curr_areaname', user.areaName)
      utils.set('jczc_curr_areaid', user.areaId)

      if (user.roleIdList && user.roleIdList.length > 1) {
        let item
        for (let i = 0; i < user.roleIdList.length; i++) {
          item = user.roleIdList[i]

          if (item !== '1000000002' && this.enableRole(item)) {
            utils.set('jczc_curr_roleid', item)
          }
        }
      } else {
        utils.set('jczc_curr_roleid', user.roleId)
      }
      utils.set('jczc_curr_roleidlist', user.roleIdList)

      // 缓存角色的
      if (user.userRoleExts && user.userRoleExts.length > 0) {
        let item
        let userRoleExts = ''
        for (let i = 0; i < user.userRoleExts.length; i++) {
          item = user.userRoleExts[i]
          userRoleExts += item.roleId + '_' + item.gradeId + '_' + item.subjectId + ','

          if (utils.get('jczc_curr_roleid') === item.roleId) {
            if (item.gradeId) {
              utils.set('jczc_curr_gradeid', item.gradeId)
            }
            if (item.subjectId) {
              utils.set('jczc_curr_subjectid', item.subjectId)
            }
          }
        }
        utils.set('jczc_userrole_exts', userRoleExts)
      }
    },
    logOut: function () {
      let vm = this
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let token = utils.get('jczc_curr_token')
        vm.clearCookieInfo()
        vm.$axios.get('/openapi-uc/oauth2.0/logout', {headers: {'Access-Token': token}})
          .then(function (response) {
            window.location.href = vm.loginUrl
          })
          .catch(function (error) {
            console.log('/openapi-uc/oauth2.0/logout error: ' + error)
            window.location.href = vm.loginUrl
          })
      }).catch(() => {
        // 取消 - 不处理
      })
    },
    loginSuccessToUrl: function () {
      let currentRoleId = utils.get('jczc_curr_roleid')
      if (currentRoleId) {
        let currentRoleIdArray = currentRoleId.split(',')
        if (currentRoleIdArray.length > 1) {
          currentRoleId = currentRoleIdArray[0]
          utils.set('jczc_curr_roleid', currentRoleId)
        }

        let url = '#/'
        if (currentRoleId === '1000000002') {
          // 教师
        } else if (currentRoleId === '1000000003') {
          // 学生
        } else if (currentRoleId === '1000000004') {
          // 家长
        } else if (currentRoleId === '1000000009') {
          // 校长
        } else if (currentRoleId === '10000000013') {
          // 班主任
        } else if (currentRoleId === '10000000014') {
          // 各年级组
        } else if (currentRoleId === '10000000015') {
          // 各学科组
        } else if (currentRoleId === '10000000016') {
          // 学生发展中学
        } else if (currentRoleId === '10000000017') {
          // 教务处
        }

        // 根据角色跳转页面
        window.location.href = url
        window.location.reload()
      } else {
        this.$message({
          message: '当前登录用户没有角色，不能正常访问',
          type: 'warning'
        })
      }
    },
    getUserCurrentUserId: function () {
      return utils.get('jczc_curr_userid')
    },
    getUserCurrentRoleId: function () {
      return utils.get('jczc_curr_roleid')
    },
    getUserUserName: function () {
      return utils.get('jczc_curr_realname')
    },
    getUserCurrentGradeId: function () {
      // 获取当前用户关联的年级Id
      let currentGradeId = utils.get('jczc_curr_gradeid')
      if (currentGradeId) {
        return currentGradeId
      }
      return ''
    },
    getUserCurrentSubjectId: function () {
      // 获取当前用户关联的科目Id
      let currentGradeId = utils.get('jczc_curr_subjectid')
      if (currentGradeId) {
        return currentGradeId
      }
      return ''
    },
    getMyRoleList: function () {
      return utils.get('jczc_curr_roleidlist')
    },
    containMenuItem: function (itemStr) {
      let show = false
      let rightpath = utils.get('jczc_curr_rightarray')
      if (rightpath) {
        let pathArray = utils.get('jczc_curr_rightarray').split(',')
        // console.log('pathArray =' + JSON.stringify(pathArray))
        let itemArray = itemStr.split(',')
        if (itemArray && itemArray.length > 0) {
          for (let i = 0; i < itemArray.length; i++) {
            if (this.arrayContainsValue(pathArray, itemArray[i])) {
              show = true
              break
            }
          }
        } else {
          // 兼容 - 如果没有获取到权限，也显示
          show = true
        }
      }
      return show
    },
    arrayContainsValue: function (arr, obj) {
      var i = arr.length
      while (i--) {
        if (arr[i] === obj) {
          return true
        }
      }
      return false
    },
    getRoleName: function (roleId) {
      let roleName = ''
      if (roleId === '1000000002') {
        roleName = '教师'
      } else if (roleId === '1000000003') {
        roleName = '学生'
      } else if (roleId === '1000000004') {
        roleName = '家长'
      } else if (roleId === '1000000009') {
        roleName = '校长'
      } else if (roleId === '10000000013') {
        roleName = '班主任'
      } else if (roleId === '10000000014') {
        roleName = '各年级组'
      } else if (roleId === '10000000015') {
        roleName = '各学科组'
      } else if (roleId === '10000000016') {
        roleName = '学生发展中学'
      } else if (roleId === '10000000017') {
        roleName = '教务处'
      }
      return roleName
    },
    enableRole: function (roleId) {
      let flag = false
      if (roleId === '1000000002' || roleId === '1000000003' || roleId === '1000000004' || roleId === '1000000009' || roleId === '10000000013' || roleId === '10000000014' || roleId === '10000000015' || roleId === '10000000016' || roleId === '10000000017' || roleId === '1000000006') {
        flag = true
      }
      return flag
    },
    changeRole: function (roleId) {
      if (!roleId) {
        return
      }
      let vm = this
      vm.$confirm('确定要切换角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 切换角色
        utils.set('jczc_curr_rightarray', '888')
        utils.set('jczc_curr_roleid', roleId)
        vm.getUserRightRequest(function () {
          // 跳转首页
          vm.loginSuccessToUrl()
        }, function (error) {
          console.log('changeRole getUserRightRequest error: ' + error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    failedToLogin: function () {
      let vm = this
      vm.$alert('登录失败，请重新登录！', '系统提示', {
        confirmButtonText: '确定',
        callback: action => {
          window.location.href = vm.loginUrl
        }
      })
    },
    getUserGrade (successCallback) {
      let vm = this
      let currentRoleId = vm.getUserCurrentRoleId()
      console.log('当前角色ID：' + currentRoleId)
      if (currentRoleId === '1000000002' || currentRoleId === '10000000013' || currentRoleId === '1000000003' || currentRoleId === '1000000004') {
        // 教师、班主任 查看自己的任教班级  学生、家长 查看自己班级的
        vm.getUserClassGrade(function (gradeIdList) {
          if (successCallback) {
            successCallback(gradeIdList)
          }
        })
      } else if (currentRoleId === '10000000014' || currentRoleId === '10000000015') {
        // 各年级组、各学科组
        let rightGradeId = vm.getUserCurrentGradeId()
        if (rightGradeId) {
          let rightGradeIdArray = rightGradeId.split(',')
          if (successCallback) {
            successCallback(rightGradeIdArray)
          }
        } else {
          if (successCallback) {
            successCallback([])
          }
        }
      } else if (currentRoleId === '1000000009' || currentRoleId === '10000000017' || currentRoleId === '10000000016') {
        // 校长 或是 教务处、学生发展中心, 查看所有的
        let rightGradeId = vm.getUserCurrentGradeId()
        if (rightGradeId) {
          let rightGradeIdArray = rightGradeId.split(',')
          if (successCallback) {
            successCallback(rightGradeIdArray)
          }
        } else {
          if (successCallback) {
            successCallback([])
          }
        }
      } else {
        if (successCallback) {
          successCallback([])
        }
      }
    },
    // 获取教师等任教、班主任等年纪信息
    getUserClassGrade (successCallback) {
      let vm = this
      let req = {}
      req.userId = vm.getUserCurrentUserId()
      req.roleId = vm.getUserCurrentRoleId()
      req.classType = '2'
      this.$axios.post('/openapi-base/base/queryUserGradeClass', req).then((resp) => {
        if (resp && resp.data && resp.data.pageInfo && resp.data.pageInfo.list && resp.data.pageInfo.list.length > 0) {
          let gradeIdList = []
          let item
          for (let i = 0; i < resp.data.pageInfo.list.length; i++) {
            item = resp.data.pageInfo.list[i]
            if (item.gradeId) {
              gradeIdList.push(item.gradeId)
            }
          }
          if (successCallback) {
            successCallback(gradeIdList)
          }
        }
      }).catch((err) => {
        if (successCallback) {
          successCallback([])
        }
        console.log(err)
      })
    }
  }
}
/*
*
1000000002 教师
1000000003 学生
1000000004 家长
1000000009  校长
'10000000013', '班主任'
'10000000014', '年级组长'
'10000000015', '学科组长'
'10000000016', 学生发展中心'
'10000000017', '教务处'
* **/
